package org.esk.dablog.web.filters;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Date;

/**
 * This class used to log incoming requests
 * User: esk
 * Date: 21.12.2006
 * Time: 20:27:01
 * $Id:$
 */
public class StatisticsFilter extends JdbcDaoSupport implements Filter {
    private static final String INSERT_QUERY =
            "insert into STAT_LOG " +
                    " (ID, REQUEST_TIME, REMOTE_USER, REMOTE_ADDRESS, REMOTE_HOST, " +
                    " REQUEST_URI, REFERRER_STRING) VALUES ( " +
                    " SEQ_STAT_LOG.nextval, ?, ?, ?, ?, ?, ?)";

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String remoteUser = request.getRemoteUser();
        String remoteAddress = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        String requestUri = request.getRequestURI();
        String referer = "";
        for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String header = (String) e.nextElement();
            if(header.toUpperCase().startsWith("REF")) {
                referer = request.getHeader(header);
                break;
            }
        }
        getJdbcTemplate().update(INSERT_QUERY, new Object[] {
                new Date(), remoteUser, remoteAddress, remoteHost,
                requestUri, referer});
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {

    }
}
